package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.NursingProjectDto;
import com.zzyl.entity.NursingProject;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.NursingProjectMapper;
import com.zzyl.mapper.NursingProjectPlanMapper;
import com.zzyl.service.NursingProjectService;
import com.zzyl.vo.NursingProjectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NursingProjectServiceImpl implements NursingProjectService {

    @Autowired
    private NursingProjectMapper nursingProjectMapper;


    @Override
    public PageResponse<NursingProjectVo> selectByPage(String name, Integer status, Integer pageNum, Integer pageSize) {
        // 借助PageHelper做分页
        PageHelper.startPage(pageNum,pageSize);
        // 紧接着一个查询方法
        Page<NursingProjectVo> page = (Page<NursingProjectVo>)nursingProjectMapper.selectByPage(name,status);

        // 把page转成PageResponse
        return PageResponse.of(page, NursingProjectVo.class);
    }

    @Override
    public void add(NursingProjectDto nursingProjectDto) {

        // 1、把dto转成实体类   属性名和类型是一致的
        NursingProject nursingProject = BeanUtil.toBean(nursingProjectDto, NursingProject.class);
        // 2、补充默认的属性   Mybatis自动补充  创建时间 更新时间 创建人
        nursingProjectMapper.add(nursingProject);

    }

    @Override
    public NursingProjectVo getById(Long id) {
        // 查询实体类
       // 实体类转成VO
      return   nursingProjectMapper.getById(id);
    }

    @Override
    public void update(NursingProjectDto nursingProjectDto) {
        // 1、把dto转成实体类   属性名和类型是一致的
        NursingProject nursingProject = BeanUtil.toBean(nursingProjectDto, NursingProject.class);
        // 2、补充默认的属性   Mybatis自动补充   更新时间 更新人
        nursingProjectMapper.update(nursingProject);

    }

    @Override
    public void updateStatus(Long id, Integer status) {
        // 根据id修改状态
        NursingProject np = new NursingProject();
        np.setStatus(status);
        np.setId(id);
        nursingProjectMapper.update(np);
    }

    @Override
    public List<NursingProjectVo> getAll() {
        return nursingProjectMapper.selectByPage(null,null);

    }

    @Autowired
    private NursingProjectPlanMapper nursingProjectPlanMapper;

    @Override
    public void deleteById(Long id) {
        // 先查询是否被护理计划使用：从中间表查数据
       Integer count =   nursingProjectPlanMapper.countByProjectId(id);
       if(count>0){
           throw new BaseException(BasicEnum.NURSING_PROJECT_IS_USE);
       }
       nursingProjectMapper.deleteById(id);
    }
}
